﻿using System;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Collections.Generic;

namespace TagSearch
{
    public class IClass
    {
        protected List<IClass> Plugins;
        protected Dictionary<String, List<ITag>> _TempResult;
        protected Dictionary<String, int> _TempCheck;
        internal JsonParser JParse;
        public IClass(params IClass[] plugins)
        {
            if (plugins.Count() > 0)
            {
                _TempCheck = new Dictionary<string, int>();
                _TempResult = new Dictionary<string, List<ITag>>();
                Plugins = new List<IClass>();
                Plugins.AddRange(plugins);
                Plugins.ForEach(n => n.CompleteEvent += (s, r) => { _TempResult[s].AddRange(r); _TempCheck[s]++; });
            }
        }
        public virtual void Search(string Name)
        {
            if (!_TempResult.ContainsKey(Name))
            {
                _TempResult.Add(Name, new List<ITag>());
                _TempCheck.Add(Name, 0);
                Plugins.ForEach(n => n.GetInfo(Name));
                while (_TempCheck[Name] != Plugins.Count) { System.Threading.Thread.Sleep(1000); }
                _TempCheck.Remove(Name);
            }
            OnEvent(Name, _TempResult[Name]);
        }

        public delegate void GetInfoComplateHandler(string Name, List<ITag> Result);
        public virtual event GetInfoComplateHandler CompleteEvent;
        protected void OnEvent(string s, List<ITag> e)
        {
            if (CompleteEvent != null)
                CompleteEvent(s, e);
        }
        protected virtual void GetInfo(string searchName)
        {
            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
        ~IClass() { GC.Collect(); GC.WaitForPendingFinalizers(); }
    }
}
